<template>
  <div class="node-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>节点管理</h2>
      <p class="page-desc">管理流程编排中的节点定义，支持动态配置节点参数</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-form :model="queryForm" inline class="search-form">
        <el-form-item label="节点编码">
          <el-input
            v-model="queryForm.nodeCode"
            placeholder="请输入节点编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="节点名称">
          <el-input
            v-model="queryForm.nodeName"
            placeholder="请输入节点名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="节点类型">
          <el-select
            v-model="queryForm.nodeType"
            placeholder="请选择节点类型"
            clearable
            style="width: 150px"
          >
            <el-option label="开始节点" value="START" />
            <el-option label="结束节点" value="END" />
            <el-option label="通用节点" value="COMMON" />
            <el-option label="条件节点" value="CONDITION" />
            <el-option label="循环节点" value="LOOP" />
          </el-select>
        </el-form-item>
        <el-form-item label="节点分类">
          <el-select
            v-model="queryForm.category"
            placeholder="请选择节点分类"
            clearable
            style="width: 150px"
          >
            <el-option label="系统内置" value="SYSTEM" />
            <el-option label="HTTP请求" value="HTTP" />
            <el-option label="脚本执行" value="SCRIPT" />
            <el-option label="条件判断" value="CONDITION" />
            <el-option label="数据处理" value="DATA" />
            <el-option label="业务逻辑" value="BUSINESS" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd" :icon="Plus">
          新增节点
        </el-button>
        <el-button type="success" @click="handleBatchEnable" :disabled="!hasSelection">
          批量启用
        </el-button>
        <el-button type="warning" @click="handleBatchDisable" :disabled="!hasSelection">
          批量禁用
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!hasSelection">
          批量删除
        </el-button>
        <el-button type="info" @click="handleExport">
          导出配置
        </el-button>
        <el-button type="info" @click="handleImport">
          导入配置
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="nodeCode" label="节点编码" width="150" />
        <el-table-column prop="nodeName" label="节点名称" width="200" />
        <el-table-column prop="nodeType" label="节点类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getNodeTypeTagType(row.nodeType)">
              {{ getNodeTypeLabel(row.nodeType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="节点分类" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)">
              {{ getCategoryLabel(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="isSystem" label="系统内置" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isSystem === 1 ? 'success' : 'info'">
              {{ row.isSystem === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
              :disabled="row.isSystem === 1"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="400" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-container">
              <el-button type="primary" size="small" @click="handleView(row)" :icon="View">
                查看
              </el-button>
              <el-button type="success" size="small" @click="handleEdit(row)" :icon="Edit">
                编辑
              </el-button>
              <el-button type="info" size="small" @click="handleCopy(row)" :icon="CopyDocument">
                复制
              </el-button>
              <el-button type="warning" size="small" @click="handleTest(row)" :icon="VideoPlay">
                测试
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
                :icon="Delete"
                :disabled="row.isSystem === 1"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 节点详情/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <NodeForm
        v-if="dialogVisible"
        :node-data="currentNode"
        :mode="dialogMode"
        @save="handleSave"
        @cancel="handleCancel"
      />
    </el-dialog>

    <!-- 节点测试对话框 -->
    <el-dialog
      v-model="testDialogVisible"
      title="节点测试"
      width="60%"
      :close-on-click-modal="false"
    >
      <NodeTest
        v-if="testDialogVisible"
        :node-data="currentNode"
        @close="testDialogVisible = false"
      />
    </el-dialog>

    <!-- 导入配置对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入节点配置"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        accept=".json"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 JSON 格式的配置文件
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmImport">确认导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  View,
  Edit,
  Delete,
  CopyDocument,
  VideoPlay,
  UploadFilled
} from '@element-plus/icons-vue'
import NodeForm from './components/NodeForm.vue'
import NodeTest from './components/NodeTest.vue'
import * as nodeDefinitionApi from '@/api/nodeDefinition'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const dialogVisible = ref(false)
const testDialogVisible = ref(false)
const importDialogVisible = ref(false)
const dialogMode = ref('view') // view, add, edit
const currentNode = ref(null)
const importFile = ref(null)

// 查询表单
const queryForm = reactive({
  nodeCode: '',
  nodeName: '',
  nodeType: '',
  category: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 计算属性
const hasSelection = computed(() => selectedRows.value.length > 0)
const dialogTitle = computed(() => {
  const titles = {
    view: '查看节点',
    add: '新增节点',
    edit: '编辑节点'
  }
  return titles[dialogMode.value]
})

// 节点类型标签样式
const getNodeTypeTagType = (type) => {
  const typeMap = {
    START: 'success',
    END: 'danger',
    COMMON: 'primary',
    CONDITION: 'warning',
    LOOP: 'info'
  }
  return typeMap[type] || 'default'
}

// 节点类型标签文本
const getNodeTypeLabel = (type) => {
  const typeMap = {
    START: '开始节点',
    END: '结束节点',
    COMMON: '通用节点',
    CONDITION: '条件节点',
    LOOP: '循环节点'
  }
  return typeMap[type] || type
}

// 节点分类标签样式
const getCategoryTagType = (category) => {
  const categoryMap = {
    SYSTEM: 'success',
    HTTP: 'primary',
    SCRIPT: 'warning',
    CONDITION: 'info',
    DATA: 'default',
    BUSINESS: 'danger'
  }
  return categoryMap[category] || 'default'
}

// 节点分类标签文本
const getCategoryLabel = (category) => {
  const categoryMap = {
    SYSTEM: '系统内置',
    HTTP: 'HTTP请求',
    SCRIPT: '脚本执行',
    CONDITION: '条件判断',
    DATA: '数据处理',
    BUSINESS: '业务逻辑'
  }
  return categoryMap[category] || category
}

// 方法定义
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      ...queryForm,
      current: pagination.current,
      size: pagination.size
    }
    const response = await nodeDefinitionApi.getNodeDefinitionPage(params)
    tableData.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('加载数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.keys(queryForm).forEach(key => {
    queryForm[key] = ''
  })
  pagination.current = 1
  loadData()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

const handleAdd = () => {
  currentNode.value = null
  dialogMode.value = 'add'
  dialogVisible.value = true
}

const handleView = (row) => {
  currentNode.value = { ...row }
  dialogMode.value = 'view'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  currentNode.value = { ...row }
  dialogMode.value = 'edit'
  dialogVisible.value = true
}

const handleCopy = async (row) => {
  try {
    await nodeDefinitionApi.copyNodeDefinition(row.id)
    ElMessage.success('复制成功')
    loadData()
  } catch (error) {
    ElMessage.error('复制失败：' + error.message)
  }
}

const handleTest = (row) => {
  currentNode.value = { ...row }
  testDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除节点 "${row.nodeName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await nodeDefinitionApi.deleteNodeDefinition(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

const handleStatusChange = async (row) => {
  try {
    await nodeDefinitionApi.updateNodeDefinitionStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败：' + error.message)
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

const handleBatchEnable = async () => {
  try {
    const ids = selectedRows.value.map(row => row.id)
    await nodeDefinitionApi.batchUpdateNodeDefinitionStatus(ids, 1)
    ElMessage.success('批量启用成功')
    loadData()
  } catch (error) {
    ElMessage.error('批量启用失败：' + error.message)
  }
}

const handleBatchDisable = async () => {
  try {
    const ids = selectedRows.value.map(row => row.id)
    await nodeDefinitionApi.batchUpdateNodeDefinitionStatus(ids, 0)
    ElMessage.success('批量禁用成功')
    loadData()
  } catch (error) {
    ElMessage.error('批量禁用失败：' + error.message)
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个节点吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const ids = selectedRows.value.map(row => row.id)
    await nodeDefinitionApi.batchDeleteNodeDefinition(ids)
    ElMessage.success('批量删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败：' + error.message)
    }
  }
}

const handleExport = async () => {
  try {
    const response = await nodeDefinitionApi.exportNodeDefinitions()
    // 创建下载链接
    const blob = new Blob([JSON.stringify(response.data, null, 2)], {
      type: 'application/json'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `node_definitions_${new Date().getTime()}.json`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败：' + error.message)
  }
}

const handleImport = () => {
  importDialogVisible.value = true
}

const handleFileChange = (file) => {
  importFile.value = file.raw
}

const handleConfirmImport = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', importFile.value)
    await nodeDefinitionApi.importNodeDefinitions(formData)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('导入失败：' + error.message)
  }
}

const handleSave = () => {
  dialogVisible.value = false
  loadData()
}

const handleCancel = () => {
  dialogVisible.value = false
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.node-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-desc {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.upload-demo {
  margin: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 操作按钮容器样式 */
.action-buttons-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px 8px;
  align-items: center;
  justify-content: flex-start;
  line-height: 1.2;
  max-width: 100%;
}

.action-buttons-container .el-button {
  flex: 0 0 calc(25% - 6px);
  max-width: calc(25% - 6px);
  min-width: 60px;
}

/* 操作按钮样式优化 */
:deep(.el-button--small) {
  padding: 5px 12px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin: 0;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff, #3a8ee6);
  border: none;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a, #5daf34);
  border: none;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c, #f25c5c);
  border: none;
}

:deep(.el-button--warning) {
  background: linear-gradient(135deg, #e6a23c, #d19e2a);
  border: none;
}

:deep(.el-button--info) {
  background: linear-gradient(135deg, #909399, #82848a);
  border: none;
}
</style>